//
//  RealTimeTrackViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/11/24.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "RealTimeTrackViewController.h"
#import "TotalDeviceSelectedViewController.h"
#import "UIView+XL.h"
#import "PullUpMenuView.h"
#import "AccountLogin.h"
#import "NetworkCommand.h"
#import "UserModel.h"
#import "WGS84TOGCJ02.h"
#import "KCAnnotation.h"
#import "UIView+XL.h"
#import "MsgCommand.h"

#import <MBProgressHUD.h>
#import <MapKit/MapKit.h>
#import <SVProgressHUD.h>
#import <CoreLocation/CoreLocation.h>

#define ANIMATION_FRAME 100.0
#define ANIMATION_SPEED 50

@interface RealTimeTrackViewController ()<MKMapViewDelegate>

@property (strong , nonatomic) CLLocationManager * locationManager;
@property (strong , nonatomic) MKMapView *mapView;

@property (strong , nonatomic) PullUpMenuView * pullUpView;
@property (strong , nonatomic) UIView * coverView;

@property (strong, nonatomic) UserModel * userModel;

@property (strong, nonatomic) KCAnnotation *annotation;

@property (strong, nonatomic) MsgCommand *msgCommand;

@property (strong, nonatomic) NSMutableArray *realTimeTrackLineArray;//实时跟踪点数组(弃用)

@property (strong, nonatomic) NSTimer *updataTimer;

/**
 开始时间
 **/
@property (strong, nonatomic) NSDate *startDate;

@property (assign, nonatomic) CGFloat lastLatitude;
@property (assign, nonatomic) CGFloat lastLongitude;

@property (weak, nonatomic) IBOutlet UIButton *satelliteButton;
@property (weak, nonatomic) IBOutlet UIButton *fullScreenButton;
@property (weak, nonatomic) IBOutlet UIButton *locationButton;
@property (weak, nonatomic) IBOutlet UIView *topButtonView;

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *topArrowButton;
@property (weak, nonatomic) IBOutlet UILabel *topLabel;
@property (weak, nonatomic) IBOutlet UIButton *topGetLastestLocationButton;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *bottomArrowButton;
@property (weak, nonatomic) IBOutlet UILabel *bottomLabel;
@property (weak, nonatomic) IBOutlet UIButton *bottomGetLastestLocationButton;


@end

@implementation RealTimeTrackViewController

-(NSMutableArray *)realTimeTrackLineArray{
    
    if (!_realTimeTrackLineArray) {
        _realTimeTrackLineArray = [NSMutableArray array];
    }
    return _realTimeTrackLineArray;
}

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

-(MsgCommand *)msgCommand{
    
    if (!_msgCommand) {
        _msgCommand = [[MsgCommand alloc]init];
    }
    return _msgCommand;
}

-(NSDate *)startDate{
    
    if (!_startDate) {
        _startDate = [NSDate date];
    }
    return _startDate;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"Start Time %@",self.startDate);
    
    self.lastLatitude = 0;
    self.lastLongitude = 0;
    
    //设置阴影
    [self setViewShadow:self.topButtonView];
    [self setViewShadow:self.topView];
    [self setViewShadow:self.bottomView];
    
    //初始化地图
    [self locationEnable];
    [self setMap];
    
    //初始化两个view
    [self.topLabel setText:@""];
    [self.bottomLabel setText:@""];
    
    self.satelliteButton.selected = NO;
    self.fullScreenButton.selected = NO;
    
    self.topArrowButton.selected = NO;
    self.bottomArrowButton.selected = NO;
    
    
    //找位置添加大头针
    
    //实时跟踪循环

    [self searchLocationIsFirstSearch:YES];
    //10.0
//    self.updataTimer = [NSTimer scheduledTimerWithTimeInterval:10 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        
//        [self searchLocationIsFirstSearch:NO];
//        
//    }];
    
    self.updataTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(updateTimerAction) userInfo:nil repeats:YES];
    
    [self.updataTimer fire];
    
    
    
}

#pragma mark 定时器事件
-(void)updateTimerAction{
    
    [self searchLocationIsFirstSearch:NO];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self setPullUpMenu];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [self.coverView removeFromSuperview];
    [self.pullUpView removeFromSuperview];
    
    self.fullScreenButton.selected = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

-(void)viewDidDisappear:(BOOL)animated{
    
    //关闭屏幕常亮
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    
    [self.updataTimer invalidate];
    
}

-(void)viewDidAppear:(BOOL)animated{
    
    //屏幕常亮
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
//    if (self.updataTimer) {
//        
//        self.realTimeTrackLineArray = nil;
//        
//        [self.updataTimer fire];
//        
//        
//        
//    }
    
}

#pragma mark 查找位置
-(void)searchLocationIsFirstSearch:(BOOL)isFirstSearch{
    
    if (isFirstSearch) {
        
        [SVProgressHUD showWithStatus:@"Loading..."];
        
    }
    
    [NetworkCommand getLastStatusDataForSerialNumber:self.userModel.selectedDeviceSerialNumber Success:^(NSArray *responseObject) {
        
        NSArray *responseObject1 = responseObject;
        
        NSString *startTimeString = [NetworkCommand getTimeStringForTimeStamp:@([self.startDate timeIntervalSince1970])];
        
        NSString *endTimeString = [NetworkCommand getEndOfDayTimeStringForDate:[NSDate date]];
        
        
#warning 0000
        
//        startTimeString = @"26/04/2017 00:00:00";
        
//        endTimeString = @"26/04/2017 23:59:59";
        
//        startTimeString = @"08/05/2017 00:00:00";
//        
//        endTimeString = @"08/05/2017 23:59:59";
        
        [NetworkCommand getHistoryTrackPoiDataByTimeForStartTime:startTimeString EndTime:endTimeString Success:^(NSArray *responseObject) {
            
            //判断有无数据
            if (responseObject1.count > 0) {
                
                if ([[responseObject1 firstObject] class] == [NSNull class]) {
                    
                    if (isFirstSearch) {
                        
                        [SVProgressHUD showErrorWithStatus:@"No Data."];
                        
                        [SVProgressHUD dismissWithDelay:1];
                        
                    }
                    
                    return;
                    
                }
                
            }else{
                
                if (isFirstSearch) {
                    
                    [SVProgressHUD showErrorWithStatus:@"No Data."];
                    
                    [SVProgressHUD dismissWithDelay:1];
                    
                }
                
                return;
                
            }
            
            [SVProgressHUD dismiss];
            
            if (responseObject.count > 0) {
                
                if ([[responseObject firstObject] class] == [NSNull class]) {
                    
                    [self addAnnotationForResponseObject:responseObject1 isFirstSearch:isFirstSearch];
                    
                }else{
                    
                    [self addAnnotationForResponseObject:responseObject isFirstSearch:isFirstSearch];
                    
                    if (responseObject.count > 1) {
                        
                        [self addLineForResponseObject:responseObject];
                        
                    }
                    
                    
                }
                
            }else{
                
                [self addAnnotationForResponseObject:responseObject1 isFirstSearch:isFirstSearch];
                
            }
            
            NSLog(@"responseObject1:%@ \n responseObject:%@",responseObject1,responseObject);
            
            [self.pullUpView setUpPullUpViewForTrackPoiDataResponseObject:responseObject StatusDataResponseObject:responseObject1];

            
        } failure:^{
            
            if (isFirstSearch) {
                
                [SVProgressHUD showErrorWithStatus:@"No Data."];
                
                [SVProgressHUD dismissWithDelay:1];
                
            }
            
        }];
        
    } failure:^{
        
        if (isFirstSearch) {
            
            [SVProgressHUD showErrorWithStatus:@"No Data."];
            
            [SVProgressHUD dismissWithDelay:1];
            
        }
        
    }];
    
}

#pragma mark 实时跟踪(弃用)
-(void)updateLocationForArrayCount:(NSInteger)count{
    
    [NetworkCommand getLastStatusDataForSerialNumber:self.userModel.selectedDeviceSerialNumber Success:^(NSArray *responseObject) {
        
        NSArray *responseObject1 = responseObject;
        
        
        
        [NetworkCommand getLastTrackPoiDataBySnsForSerialNumber:self.userModel.selectedDeviceSerialNumber Success:^(NSArray *responseObject) {
            
            //判断有无数据
            if (responseObject.count > 0) {
                
                if ([[responseObject firstObject] class] == [NSNull class] || [[responseObject1 firstObject] class] == [NSNull class]) {
                    
                    return;
                    
                }
                
            }else{
                
                return;
                
            }
            
            
            //判断是否相同
            NSInteger count = self.realTimeTrackLineArray.count;
            
            if (count > 0) {
                
                NSDictionary *dict1 = self.realTimeTrackLineArray[count - 1];
                NSDictionary *dict2 = [responseObject1 firstObject];
                
                NSNumber *latitude1 = [dict1 valueForKey:NC_LAT];
                NSNumber *longitude1 = [dict1 valueForKey:NC_LNG];
                
                NSNumber *latitude2 = [dict2 valueForKey:NC_LAT];
                NSNumber *longitude2 = [dict2 valueForKey:NC_LNG];
                
                if ([latitude1 isEqual:latitude2] && [longitude1 isEqual:longitude2]) {
                    
                    return;
                    
                }
                
                //是否超时
                if (self.realTimeTrackLineArray.count > count) {
                    
                    return;
                    
                }
                
            }
            
            
            
            //添加
            
            [self.mapView removeAnnotations:self.mapView.annotations];
            
//            [self addAnnotationForResponseObject:responseObject1];
            
            [self.pullUpView setUpPullUpViewForTrackPoiDataResponseObject:responseObject StatusDataResponseObject:responseObject1];
            
            //画线
            NSDictionary *dict = [responseObject1 firstObject];
            
            [self.realTimeTrackLineArray addObject:dict];
            
//            [self addTwoPointLink];
            
        } failure:^{
            
            return;
            
        }];
        
    } failure:^{
        
        return;
        
    }];
    
}

#pragma mark 添加大头针
-(void)addAnnotationForResponseObject:(NSArray *)responseObject isFirstSearch:(BOOL)isFirstSearch{
    
    NSString *serialNumber = self.userModel.selectedDeviceSerialNumber;
    
    NSDictionary *dict = [responseObject lastObject];
    
    NSNumber *latitude = [dict valueForKey:NC_LAT];
    
    NSNumber *longitude = [dict valueForKey:NC_LNG];
    
    //判断是否与上个点相同
    if (_lastLatitude != 0 && _lastLongitude != 0) {
        
        if (_lastLatitude == [latitude floatValue] && _lastLongitude == [longitude floatValue]) {
            return;
        }
        
    }
    
    if ([latitude floatValue] != 0 && [longitude floatValue] != 0) {
        
        
        //获取准确坐标
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake([latitude doubleValue], [longitude doubleValue]);
        
        
        CLLocationCoordinate2D fixLocation;
        
        if (![WGS84TOGCJ02 isLocationOutOfChina:location]) {
            
            fixLocation = [WGS84TOGCJ02 transformFromWGSToGCJ2:location];
            
        }else{
            
            fixLocation = location;
            
        }
        
        
        
        self.annotation = [[KCAnnotation alloc]init];
        self.annotation.coordinate = fixLocation;
        
        //合成图片
        NSInteger powerValue = [[dict valueForKey:NC_POWER_VALUE] integerValue];
        
        UIImage *powerImage;
        
        if (powerValue >= 70) {
            
            powerImage = [UIImage imageNamed:@"ic_power_full"];
            
        }else if (powerValue < 70 && powerValue >= 20){
            
            powerImage = [UIImage imageNamed:@"ic_power_medium"];
            
        }else{
            
            powerImage = [UIImage imageNamed:@"ic_power_low"];
            
        }
        
        UIImage *iconImage = [self.userModel.deviceIconDictionary valueForKey:serialNumber];
        
        if (!iconImage) {
            
            iconImage = [UIImage imageNamed:@"ic_tracker_useractivity_yuan_2"];
            
        }
        
        
        NSString *deviceName = serialNumber;
        
        if ([self.userModel.changeDeviceNameDictionary valueForKey:serialNumber]) {
            
            deviceName = [self.userModel.changeDeviceNameDictionary valueForKey:serialNumber];
            
        }else{
            
            for (NSDictionary *dict in self.userModel.deviceByAccountArray) {
                
                if ([[dict valueForKey:NC_SERIAL_NUMBER] isEqualToString:serialNumber]) {
                    
                    deviceName = [dict valueForKey:NC_DISPLAY_NAME];

                    break;
                }
                
            }
            
        }
        
        
        
        self.annotation.image = [self addImage:[UIImage imageNamed:@"ic_track_marker_boy_2"] toImage:iconImage powerImage:powerImage powerValue:powerValue deviceName:deviceName];
        
        [_mapView removeAnnotations:self.mapView.annotations];
        
        [_mapView addAnnotation:_annotation];
        
        NSLog(@"add annotation %@",serialNumber);
        
        
        
        
        double eyeAltitude;
        
        if (_mapView.camera.altitude > STATIC_ALTITUDE) {
            
            eyeAltitude = STATIC_ALTITUDE;
            
        }else{
            
            eyeAltitude = _mapView.camera.altitude;
            
        }
        
        _lastLatitude = [latitude floatValue];
        _lastLongitude = [longitude floatValue];
        
        //移动到大头针位置
        MKMapCamera *mkMapCamera = [MKMapCamera cameraLookingAtCenterCoordinate:fixLocation fromEyeCoordinate:fixLocation eyeAltitude:eyeAltitude];
        
        if (fabs(fixLocation.latitude) <= 90 && fabs(fixLocation.longitude) < 180 ) {
            [_mapView setCamera:mkMapCamera animated:YES];
        }
        
        
        NSLog(@"altitude %f",_mapView.camera.altitude);
        
        
    }else{
        
        if (isFirstSearch) {
            
            [SVProgressHUD showErrorWithStatus:@"No Data."];
            
            [SVProgressHUD dismissWithDelay:1];
            
        }

        
    }
    
    
    
}

#pragma mark 合成图片

- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 powerImage:(UIImage *)powerImage powerValue:(NSInteger)powerValue deviceName:(NSString *)deviceName{
    
    //    CGFloat circleWidth = powerImage.size.width + 15;
    
    NSDictionary *deviceNameAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect deviceNameSizeToFit = [deviceName boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:deviceNameAttributes context:nil];
    
    NSLog(@"deviceNameSizeToFit %f",deviceNameSizeToFit.size.width);
    
    
    NSLog(@"image1 %f",image1.size.width);
    
    
    //info图片
    
    
    
    
    //电量string
    NSString *powerString = [NSString stringWithFormat:@"%ld%%",(long)powerValue];
    
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect sizeToFit = [powerString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil];
    
    
    
    
    CGFloat infoHeight = deviceNameSizeToFit.size.height + powerImage.size.height + 15;
    
    CGFloat infoWidth;
    
    CGFloat margin;
    
    CGFloat deviceNameX;
    
    if (powerImage.size.width + sizeToFit.size.width + 5 > deviceNameSizeToFit.size.width) {
        
        infoWidth = powerImage.size.width + sizeToFit.size.width + 25;
        
        margin = (infoWidth - powerImage.size.width - sizeToFit.size.width)/2;
        
        deviceNameX = (infoWidth - deviceNameSizeToFit.size.width) / 2 ;
        
    }else{
        
        infoWidth = deviceNameSizeToFit.size.width + 20;
        
        margin = (infoWidth - powerImage.size.width - sizeToFit.size.width)/2 + 5;
        
        deviceNameX = 10;
        
    }
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(infoWidth, infoHeight), NO, 0.0);
    
    
    
    
    
    
    UIImage *infoImage = [UIImage imageNamed:@"power&username2"];
    
    [infoImage drawInRect:CGRectMake(0, 0, infoWidth, infoHeight)];
    
    [deviceName drawAtPoint:CGPointMake(deviceNameX, 5) withAttributes:deviceNameAttributes];
    
    
    
    
    [powerString drawAtPoint:CGPointMake(margin + powerImage.size.width + 5,deviceNameSizeToFit.size.height + 10) withAttributes:attributes];
    
    [powerImage drawAtPoint:CGPointMake(margin,deviceNameSizeToFit.size.height + 10)];
    
    
    
    
    UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    CGFloat infoImageMarginHeight = circleImage.size.height / 2;
    
    //大头针
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image1.size.width + circleImage.size.width, image1.size.height + infoImageMarginHeight), NO, 0.0);
    
    // Draw image1
    [image1 drawInRect:CGRectMake(0, infoImageMarginHeight, image1.size.width, image1.size.height)];
    
    // Draw image2
    [image2 drawInRect:CGRectMake(2, infoImageMarginHeight + 2, image1.size.width - 4, image1.size.width - 4)];
    
    [circleImage drawInRect:CGRectMake(image1.size.width, 0, circleImage.size.width, circleImage.size.height)];
    
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}


//- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 powerImage:(UIImage *)powerImage powerValue:(NSInteger)powerValue{
//    
//    CGFloat circleWidth = powerImage.size.width + 15;
//    
//    UIGraphicsBeginImageContextWithOptions(CGSizeMake(circleWidth, circleWidth), NO, 0.0);
//    
//    //画圆
//    
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    [[UIColor clearColor] set];
//    CGContextFillRect(context, CGRectMake(0, 0, circleWidth, circleWidth));
//    CGContextAddEllipseInRect(context, CGRectMake(0, 0, circleWidth, circleWidth));
//    [[UIColor colorWithRed:80/255.0 green:150/255.0 blue:240/255.0 alpha:1] set];
//    CGContextFillPath(context);
//    
//    
//    
//    //电量数字
//    NSString *powerString = [NSString stringWithFormat:@"%ld%%",(long)powerValue];
//    
//    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
//    
//    CGRect sizeToFit = [powerString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil];
//    
//    
//    
//    
//    [powerString drawAtPoint:CGPointMake((circleWidth-sizeToFit.size.width)/2,5) withAttributes:attributes];
//    
//    [powerImage drawAtPoint:CGPointMake((circleWidth - powerImage.size.width)/2, 5 + powerImage.size.height)];
//    
//    
//    UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    
//    //大头针
//    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image1.size.width + circleImage.size.width, image1.size.height + circleWidth/2), NO, 0.0);
//    
//    // Draw image1
//    [image1 drawInRect:CGRectMake(0, circleWidth/2, image1.size.width, image1.size.height)];
//    
//    // Draw image2
//    [image2 drawInRect:CGRectMake(2, circleWidth/2 + 2, image1.size.width - 4, image1.size.width - 4)];
//    
//    [circleImage drawInRect:CGRectMake(image1.size.width, 0, circleImage.size.width, circleImage.size.height)];
//    
//    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    return resultingImage;
//}

#pragma mark - 地图控件代理方法
#pragma mark 显示大头针时调用，注意方法中的annotation参数是即将显示的大头针对象
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        
        //算中心点
        CGFloat pointCenterPercent = 30.0 / ((KCAnnotation *)annotation).image.size.width;
        
        NSLog(@"pointCenterPercent %f",pointCenterPercent);
        
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
            annotationView.calloutOffset=CGPointMake(0, 0);//定义详情视图偏移量
            annotationView.layer.anchorPoint = CGPointMake(pointCenterPercent, 1);
            annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定义详情左侧视图
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片
        
        
        return annotationView;
    }else {
        return nil;
    }
}


#pragma mark 初始化上拉菜单
-(void)setPullUpMenu{
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    self.pullUpView = [[PullUpMenuView alloc]initWithPullUpMenuView];
    
    [self setViewShadow:self.pullUpView];
    
    self.coverView = [[UIView alloc]initWithFrame:CGRectMake(0, [[UIApplication sharedApplication] statusBarFrame].size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - [[UIApplication sharedApplication] statusBarFrame].size.height)];
    
    [self.coverView setBackgroundColor:[UIColor blackColor]];
    
    __block RealTimeTrackViewController * safeSelf = self;
    
    self.pullUpView.changeCoverViewAlpha = ^(CGFloat pullUpMenuViewY){
    
        safeSelf.coverView.alpha = ([UIScreen mainScreen].bounds.size.height - pullUpMenuViewY - 30) / ([UIScreen mainScreen].bounds.size.height - [[UIApplication sharedApplication] statusBarFrame].size.height - 30) / 2;
    
    };
    
    self.coverView.alpha = 0;
    
    [window addSubview:self.coverView];
    
    [window addSubview:self.pullUpView];
    
}

#pragma mark 按钮阴影效果
-(void)setViewShadow:(UIView *)sender{
    
    sender.layer.shadowColor = [UIColor blackColor].CGColor;
    
    sender.layer.shadowOffset = CGSizeMake(2, 2);
    
    sender.layer.shadowOpacity = 0.4;
    
    sender.layer.shadowRadius = 4;
    
}

#pragma mark 初始化地图

-(void)setMap{
    
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    [self.view addSubview:self.mapView];
    
    [self.view sendSubviewToBack:self.mapView];
    
    self.mapView.delegate = self;
    
//    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    self.mapView.mapType = MKMapTypeStandard;
    
    
    
    
}

#pragma mark 判断是否有权限
-(void)locationEnable{
    
    self.locationManager = [[CLLocationManager alloc] init];
    
//    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    
    //是否具有定位权限
    int status=[CLLocationManager authorizationStatus];
    
    //请求权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8)
    {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
    }
    
    if (status < 3 || ![CLLocationManager locationServicesEnabled]){
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"The user is not allowed to turn on the location service" message:@"Please turn on location service" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
                
            }
            
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        
        
    }
    
}

#pragma mark 模拟轨迹运动
-(void)lineAnimationForResponse:(NSArray *)response complete:(void (^)())complete{
    
    __block NSInteger index = 0;
    
    NSInteger count = response.count;
    
    NSDictionary *dict1 = response[count - 2];
    
    NSDictionary *dict2 = [response lastObject];
    
    CGFloat latitude1 = [[dict1 valueForKey:NC_LAT] floatValue];
    CGFloat longitude1 = [[dict1 valueForKey:NC_LNG] floatValue];
    
    CGFloat latitude2 = [[dict2 valueForKey:NC_LAT] floatValue];
    CGFloat longitude2 = [[dict2 valueForKey:NC_LNG] floatValue];
    
    double mLatitude = (latitude2 - latitude1) / 100.0;
    double mLongitude = (longitude2 - longitude1) / 100.0;
    
    NSTimer *lineTimer = [NSTimer timerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        
        if (index < ANIMATION_FRAME) {
            
            CLLocationCoordinate2D coods[count];
            
            for (int i = 0; i < count - 1; i++) {
                
                NSDictionary *dict = response[i];
                
                NSNumber *latitude = [dict valueForKey:NC_LAT];
                NSNumber *longitude = [dict valueForKey:NC_LNG];
                
                double newLatitude;
                double newLongitude;
                
                if (i == count - 1) {
                    
                    newLatitude = [latitude floatValue] + mLatitude * (index + 1);
                    newLongitude = [longitude floatValue] + mLongitude * (index + 1);
                    
                }else{
                    
                    newLatitude = [latitude floatValue];
                    newLongitude = [longitude floatValue];
                    
                }
                
                CLLocationCoordinate2D locationCoordinate2D = CLLocationCoordinate2DMake(newLatitude, newLongitude);
                
                if (![WGS84TOGCJ02 isLocationOutOfChina:locationCoordinate2D]) {
                    
                    locationCoordinate2D = [WGS84TOGCJ02 transformFromWGSToGCJ2:locationCoordinate2D];
                    
                }
                
                coods[i] = locationCoordinate2D;
                
            }
            
            MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coods count:count];
                
            [self.mapView removeOverlays:self.mapView.overlays];
                
            [self.mapView addOverlay:polyline];
            
            index ++;
            
        }else{
            
            complete();
            
            [timer invalidate];
            
        }
        
    }];
    
    [lineTimer fire];
    
//    private  final  Runnable  mTrackTask  =  new  Runnable()  {
//        @Override
//        public  void  run()  {
//            moveMarker();
//            checkMarkerOutsideScreen();
//            addPolyline();
//            if  (mFrameIndex  !=  FRAME)  {
//                mFrameIndex++;
//                mHandler.postDelayed(this,  SPEED);
//            }  else  {
//                mOnTrackListener.onTrackStep(mPoints.get(mPointIndex));
//                mPointIndex++;
//                if  (mPointIndex  <  mPoints.size())  {
//                    transition(mPoints.get(mPointIndex));
//                    mHandler.post(mTrackTask);
//                }  else  {
//                    mTrackState  =  TRACK_STATE_STOP;
//                    mPointIndex  =  0;
//                    mPoints.clear();
//                    mOnTrackListener.onTrackFinish();
//                }
//            }
//        }
//    };
//    
//    
//    protected  void  transition(GPSPoint  point)  {
//        mFrameIndex  =  0;
//        final  LatLng  markerPosition  =  mMoveMarker.getPosition();
//        final  LatLng  newPosition  =  BaiDuConverter.point2LatLng(point);
//        mDelayLat  =  (newPosition.latitude  -  markerPosition.latitude)  /  FRAME;
//        mDelayLng  =  (newPosition.longitude  -  markerPosition.longitude)  /  FRAME;
//    }
    
    
    
}

#pragma mark 添加路线
-(void)addLineForResponseObject:(NSArray *)responseObject{
    
    if (responseObject.count <= 1) {
        
        return;
        
    }
    
    NSInteger count = responseObject.count;
    
    CLLocationCoordinate2D coods[count];
    
    for (int i = 0; i < count; i++) {
        
        NSDictionary *dict = responseObject[i];
        
        NSNumber *latitude = [dict valueForKey:NC_LAT];
        NSNumber *longitude = [dict valueForKey:NC_LNG];
        
        CLLocationCoordinate2D locationCoordinate2D = CLLocationCoordinate2DMake([latitude doubleValue], [longitude doubleValue]);
        
        if (![WGS84TOGCJ02 isLocationOutOfChina:locationCoordinate2D]) {
            
            locationCoordinate2D = [WGS84TOGCJ02 transformFromWGSToGCJ2:locationCoordinate2D];
            
        }
        
        coods[i] = locationCoordinate2D;
        
    }
    
//    NSDictionary *dict1 = self.realTimeTrackLineArray[count - 2];
//    NSDictionary *dict2 = self.realTimeTrackLineArray[count - 1];
//    
//    NSNumber *latitude1 = [dict1 valueForKey:NC_LAT];
//    NSNumber *longitude1 = [dict1 valueForKey:NC_LNG];
//    
//    NSNumber *latitude2 = [dict2 valueForKey:NC_LAT];
//    NSNumber *longitude2 = [dict2 valueForKey:NC_LNG];
//    
//    if ([latitude1 isEqual:latitude2] && [longitude1 isEqual:longitude2]) {
//        
//        [self.realTimeTrackLineArray removeObject:dict2];
//        
//        return;
//        
//    }
//    
//    CLLocationCoordinate2D locationCoordinate2D1 = CLLocationCoordinate2DMake([latitude1 doubleValue], [longitude1 doubleValue]);
//    CLLocationCoordinate2D locationCoordinate2D2 = CLLocationCoordinate2DMake([latitude2 doubleValue], [longitude2 doubleValue]);
//    
//    if (![WGS84TOGCJ02 isLocationOutOfChina:locationCoordinate2D1]) {
//        
//        locationCoordinate2D1 = [WGS84TOGCJ02 transformFromWGSToGCJ2:locationCoordinate2D1];
//        
//        
//        
//    }
//    
//    if (![WGS84TOGCJ02 isLocationOutOfChina:locationCoordinate2D2]) {
//        
//        locationCoordinate2D2 = [WGS84TOGCJ02 transformFromWGSToGCJ2:locationCoordinate2D2];
//        
//    }
//    
//    
//    
//    coods[0] = locationCoordinate2D1;
//    coods[1] = locationCoordinate2D2;
    
    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coods count:count];
    
    [self.mapView removeOverlays:self.mapView.overlays];
    
    [self.mapView addOverlay:polyline];
    
//    [self lineAnimationForResponse:responseObject complete:^{
//        
//        [self.mapView removeOverlays:self.mapView.overlays];
//        
//        [self.mapView addOverlay:polyline];
//        
//    }];
    
    
    
}

#pragma mark 画线
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    
    //绘制线条
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *polylineRender = [[MKPolylineRenderer alloc]initWithPolyline:overlay];
        
        polylineRender.strokeColor = [UIColor redColor];
        
        polylineRender.lineWidth = 3;
        
        return polylineRender;
    }
    
    return nil;
    
}

//- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
//{
//    //绘制线条
//    if ([overlay isKindOfClass:[MKPolyline class]])
//    {
//        MKPolylineRenderer *polylineRender = [[MKPolylineRenderer alloc]initWithPolyline:overlay];
//        
//        polylineRender.strokeColor = [UIColor redColor];
//        
//        polylineRender.lineWidth = 3;
//        
//        return (MKOverlayView *)polylineRender;
//    }
//    
//    return nil;
//}

#pragma mark 卫星地图按钮点击事件
- (IBAction)changeMapType:(id)sender {
    
    if (self.satelliteButton.selected) {
        
        self.mapView.mapType = MKMapTypeStandard;
        
    }else{
        
        self.mapView.mapType = MKMapTypeSatellite;
        
    }
    
    
    self.satelliteButton.selected = !self.satelliteButton.selected;
    
}

#pragma mark 全屏按钮点击事件
- (IBAction)mapFullScreen:(id)sender {
    
    if (self.fullScreenButton.selected) {
        
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        
        
    }else{
        
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        
        
    }
    
    
    self.fullScreenButton.selected = !self.fullScreenButton.selected;
    
}

#pragma mark 打开收起label
- (IBAction)touchTopArrowButton:(id)sender {
    
    if (!self.topArrowButton.selected) {

        [self.topLabel setText:@"Get latest location with lower accuracy.But long device working time"];
        
    }else{
            
        [self.topLabel setText:@""];

    }
    
    self.topArrowButton.selected = !self.topArrowButton.selected;
    
}

- (IBAction)touchBottomArrowButton:(id)sender {
    
    if (!self.bottomArrowButton.selected) {
      
        [self.bottomLabel setText:@"Get latest location with higher accuracy.But short device working time"];
 
    }else{
        
        [self.bottomLabel setText:@""];
        
    }
    
    self.bottomArrowButton.selected = !self.bottomArrowButton.selected;
    
}

#pragma mark 定位按钮
- (IBAction)touchLocationButton:(id)sender {
    
    [self searchLocationIsFirstSearch:YES];
    
}

#pragma mark CurrentGPSLocation
- (IBAction)touchCurrentGpsLocation:(id)sender {
    
    [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:MC_TITLE_CURRENT_GPS_LOCATION body:MC_BODY_CURRENT_GPS_LOCATION];
    
}

#pragma mark CurrentLBSLocation
- (IBAction)touchCurrentLBSLocation:(id)sender {
    
    [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:MC_TITLE_CURRENT_LBS_LOCATION body:MC_BODY_CURRENT_LBS_LOCATION];
    
}

#pragma mark 点击列表按钮
- (IBAction)toucTotalDeviceButton:(id)sender {
    
    TotalDeviceSelectedViewController *totalDeviceSelectedViewController = [[TotalDeviceSelectedViewController alloc]init];
    
    [self.navigationController showViewController:totalDeviceSelectedViewController sender:nil];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
